package io.ouka.pub.response;


import io.ouka.pub.annotation.IgnoreUnified;
import io.ouka.pub.util.GsonUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.Objects;

/**
 * @author ouka
 * @ClassName ReturnAdvice
 * @Package com.sinosig.publicmodule.result
 * @Description: 统一返回
 * 扫描地址自定义为 public.return.api(缺省值为.api)
 * public.return.handler(缺省值为.exception.handler)
 * @date 2020/5/25 10:12
 */
@ControllerAdvice
public class ReturnAdvice implements ResponseBodyAdvice {
    private static final String DEFAULT_EXCEPTION_HANDLRE_END_STR =".exception.handler";
    private static final String DEFAULT_API_END_STR =".api";
    private  final String API_END_STR ;
    private  final String EXCEPTION_HANDLRE_END_STR ;
    private final boolean selfapi;
    private final boolean selfhandler;

    public ReturnAdvice(@Value("${public.return.api:.api}") String apiEnd,
                        @Value("${public.return.handler:.exception.handler}")String handlerEnd) {
        this.API_END_STR=apiEnd;
        this.EXCEPTION_HANDLRE_END_STR=handlerEnd;
        this.selfapi=apiEnd.equals(DEFAULT_API_END_STR);
        this.selfhandler=handlerEnd.equals(DEFAULT_EXCEPTION_HANDLRE_END_STR);
    }

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        IgnoreUnified annotation = returnType.getExecutable().getDeclaredAnnotation(IgnoreUnified.class);
        return (returnType.getContainingClass().getPackage().getName().endsWith(API_END_STR)||
                returnType.getContainingClass().getPackage().getName().endsWith(EXCEPTION_HANDLRE_END_STR))
                && Objects.isNull(annotation);
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if (body instanceof ResultMsg ) {
            return body;
        }
        if(body instanceof String){
            ResultMsg resultMsg = ResultMsg.wrapperBusSuccessResult(body, null);
            return GsonUtil.GsonString(resultMsg);
        }
        if (selectedContentType.includes(MediaType.APPLICATION_JSON) || selectedContentType.includes(MediaType.TEXT_HTML) || selectedContentType.includes(MediaType.TEXT_PLAIN)) {
            ResultMsg resultMsg = ResultMsg.wrapperBusSuccessResult(body, null);
            return resultMsg;
        }

        return null;
    }
}
